<template>
  <div id="app">
    <h1>{{ msg }}</h1>

    <el-form :inline="true" :model="formInline" class="demo-form-inline">
      <el-form-item label="桶名">
        <el-input v-model="bucketName" placeholder="桶名"></el-input>
      </el-form-item>
      <el-form-item label="对象名称">
        <el-input v-model="objectName" placeholder="对象名称"></el-input>
      </el-form-item>
      <el-button type="primary" @click="submit0()">删除对象</el-button>
    </el-form>

    <el-form :inline="true" :model="formInline" class="demo-form-inline">
      <el-form-item label="从字符串上传对象">
        <el-input v-model="objectContent" placeholder="字符串"></el-input>
      </el-form-item>
      <el-button type="primary" @click="submit1()">上传对象</el-button>
    </el-form>

    <el-form :inline="true" :model="formInline" class="demo-form-inline">
      <el-form-item label="从文件内容上传对象-file bufferStream">
        <input type="file" v-on:change="loadFile($event)"/>
      </el-form-item>
      <el-button type="primary" @click="submit2()">上传文件对象</el-button>
    </el-form>

    <el-form :inline="true" :model="formInline" class="demo-form-inline">
      <el-form-item label="上传文件-从file上传对象-更简单">
        <input type="file" v-on:change="loadFile($event)"/>
      </el-form-item>
      <el-button type="primary" @click="submit3()">上传文件对象</el-button>
    </el-form>

    <h4>批量上传文件</h4>
    <el-form :inline="true" :model="formInline" class="demo-form-inline">
      <el-form-item label="桶名">
        <el-input v-model="bucketName" placeholder="桶名"></el-input>
      </el-form-item>
      <el-form-item>
        <el-upload ref="upfile"
                   style="display: inline"
                   :auto-upload="false"
                   :on-change="handleChange"
                   :file-list="fileList"
                   :show-file-list="true"
                   action="#">
          <el-button type="success">选择文件</el-button>
          <el-button type="success" @click="upload()">点击上传</el-button>
        </el-upload>
      </el-form-item>
    </el-form>
    <p></p>

    <p>{{data}}</p>
    <p></p>
  </div>
</template>

<script>

  var OSS = require("oss-js-client");
  var ossBuffer = require('buffer').Buffer;

  //OSS客户端
  let ossClient = new OSS.Client({
    // endPoint: "192.168.1.40",
    endPoint: "127.0.0.1",
    port: 9000,
    useSSL: false,
    accessKey: "username",
    secretKey: "password",
  });

  //base64转bolb
  function dataURLtoBlob(dataurl) {
    var arr = dataurl.split(',');
    //注意base64的最后面中括号和引号是不转译的
    var _arr = arr[1].substring(0, arr[1].length - 2);
    var mime = arr[0].match(/:(.*?);/)[1],
      bstr = atob(_arr),
      n = bstr.length,
      u8arr = new Uint8Array(n);
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], {
      type: mime
    });
  };

  //上传文件
  function uploadFile(bucketName, file) {
    var metaData = {
      'Content-Type': file.type,
      "content-length": file.size
    }
    let reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = function (e) {
      const dataUrl = e.target.result;
      //base64转bolb
      const bolb = dataURLtoBlob(dataUrl);
      //bolb转arrayBuffer
      let reader2 = new FileReader();
      reader2.readAsArrayBuffer(bolb, 'utf8');  // utf8 防止下载的zip文件损坏
      reader2.onload = function (ex) {
        // const base64File = reader.result.replace(/^data:\w+\/\w+;base64,/, '')
        // const buffer = Buffer.from(ex.target.result, 'base64');
        let buffer = ossBuffer(ex.target.result);
        const stream = require('stream');
        var bufferStream = new stream.PassThrough();
        bufferStream.end(buffer);
        ossClient.putObject(bucketName, file.name, bufferStream, file.size, metaData, function (err, etag) {
          if (err) {
            return console.log(err) // err should be null
          }
          return console.log(err, etag);
        })
      }
    }
  };

  export default {
    name: "VueOSSObjectUpload",
    data() {
      return {
        bucketName: "mybucket2",
        objectName: "c.txt",
        objectContent: "c-content",
        formInline: {},
        file: {},
        fileList: [],
        data: '',
        msg: "演示OSSClient-ObjectUpload 上传操作",
      };
    },
    methods: {

      //获取文件
      loadFile: function (e) {
        let file = e.target.files[0];
        console.log(file);
        this.file = file;
        this.objectName = this.file.name;
      },

      submit0: function () {
        //删除一个对象
        ossClient.removeObject(this.bucketName, this.objectName, function (err) {
          if (err) {
            return console.log('Unable to remove object', err)
          }
          console.log('Removed the object success !')
        });
      },

      submit1: function () {
        //上传字符串或Buffer对象类型
        var buffer = this.objectContent;
        var metaData = {
          'Content-Type': 'text/plain', //需要设置类型
        };
        //从字符串上传对象
        //ossClient.putObject(bucketName, objectName, stream, size, metaData, callback)
        ossClient.putObject(this.bucketName, this.objectName, buffer, 0, metaData, (err, etag) => {
          // err should be null, tag 默是MD5
          if (err){
            this.data = err
            return console.log(err)
          }else {
            this.data = etag
            return console.log(etag)
          }
        })
      },

      submit2: function () {
        //上传文件内容-从file bufferStream上传对象
        uploadFile(this.bucketName, this.file);
      },

      submit3: function () {
        //上传文件-从file上传对象-更简单
        ossClient.putObjectByFile(this.bucketName, this.objectName, this.file, function (err, etag) {
          return console.log(err, etag) // err should be null, tag 默是MD5
        })
      },

      submit4: function () {
        ossClient.putObjectByFile(this.bucketName, this.objectName, this.file, function (err, etag) {
          return console.log(err, etag) // err should be null, tag 默是MD5
        })
      },


      //只展示最后一次选择的文件  只能选择单文件上传
      /*handleChange(file, fileList) {
        if (fileList.length > 0) {
          this.fileList = [fileList[fileList.length - 1]]  // 这一步，是 展示最后一次选择的文件
        }
      },*/

      //通过onchanne触发方法获得文件列表
      handleChange(file, fileList) {
        this.fileList = fileList;
        console.log(fileList)
      },

      upload() {
        //表单数据
        // let fd = new FormData();
        this.fileList.forEach(item => {
          //文件信息中raw才是真的文件
          ossClient.putObjectByFile(this.bucketName, item.name, item.raw, function (err, etag) {
            return console.log(err, etag) // err should be null, tag 默是MD5
          });
        });
      },

    }
  }
  ;
</script>

<style scope>
</style>
